<template>
  <div class="main-context">
    <canvas id="bg-canvas"></canvas>
    <el-card class="box-card">
      <el-space direction="vertical" style="width: 100%" size="large">
        <el-space>
          <img src="../assets/logo.gif" width="100%" style="width: 80px">
          <el-space direction="vertical" style="width: 100%" size="small">
            <h2 style="font-style: oblique">欢迎登录！</h2>
          </el-space>
        </el-space>
        <el-form :model="formData" label-width="0px" ref="formRef">
          <el-form-item label="" prop="username"
                        :rules="[{required:true,message:'请输入用户名',trigger:[ 'blur','change']}]">
            <el-input
                :prefix-icon="User"
                placeholder="请输入账号"
                v-model.trim="formData.username"
                clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="" prop="password"
                        :rules="[{required:true,message:'请输入密码',trigger:[ 'blur','change']}]">
            <el-input
                :prefix-icon="Lock"
                placeholder="请输入密码"
                show-password
                style="width: 240px"
                v-model.trim="formData.password"
                clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="" prop="type">
            <el-select v-model="formData.type" placeholder="请选择用户类型" style="width: 240px">
              <el-option label="管理员" value="ADMIN"></el-option>
              <el-option label="普通用户" value="USER"></el-option>
              <el-option label="店铺" value="SHOP"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-space direction="vertical" alignment="left" style="width: 100%">
              <el-button @click="submitForm()" type="primary" style="width: 100%">登 录</el-button>
              <router-link tag="span" :to="{path:'register'}">
                <el-button link class="button" style="float: right">没有账号？去注册</el-button>
              </router-link>
            </el-space>
          </el-form-item>
        </el-form>
      </el-space>
    </el-card>
  </div>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import {ElMessage} from 'element-plus';
import http from "@/utils/http.js";
import {User, Lock} from "@element-plus/icons-vue";
import { useRouter } from 'vue-router';

const router = useRouter();
const formData = ref({
  username: '',
  password: '',
  type: 'USER'
});

const formRef = ref(null);
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      return;
    }
    http.post("/common/login", formData.value).then(res => {
      if (!res) {
        return;
      }
      ElMessage({
        message: "登录成功，正在跳转",
        type: "success"
      });
      localStorage.setItem("token", res.data);
      http.get("/common/currentUser").then(res1 => {
        let currentUser = res1.data;
        localStorage.setItem("currentUser", JSON.stringify(currentUser));
        http.get("/common/currentUser").then(res1 => {
          let currentUser = res1.data;
          localStorage.setItem("currentUser", JSON.stringify(currentUser));
          if (currentUser.type === 'ADMIN') {
            router.push({ path: '/admin' });
          } else if (currentUser.type === 'USER') {
            router.push({ path: '/front' });
          } else if (currentUser.type === 'SHOP') {
            router.push({ path: '/shop' });
          } else {
            ElMessage({
              message: "用户类型错误",
              type: "error"
            });
          }
        })
      });
    });
  });
};

// Canvas背景动画
onMounted(() => {
  const canvas = document.getElementById('bg-canvas');
  const ctx = canvas.getContext('2d');
  let width = window.innerWidth;
  let height = window.innerHeight;
  
  // 设置canvas尺寸
  canvas.width = width;
  canvas.height = height;
  
  // 创建背景图片
  const backgroundImage = new Image();
  backgroundImage.src = new URL('../assets/login.png', import.meta.url).href; // 使用login.png作为背景
  
  // 视差参数
  let mouseX = 0;
  let mouseY = 0;
  let targetX = 0;
  let targetY = 0;
  const parallaxStrength = 20; // 降低视差强度，使效果更柔和
  
  // 监听鼠标移动
  const handleMouseMove = (e) => {
    mouseX = (e.clientX - width / 2) / (width / 2);
    mouseY = (e.clientY - height / 2) / (height / 2);
  };
  
  window.addEventListener('mousemove', handleMouseMove);
  
  // 动画循环
  function animate() {
    // 平滑过渡，降低移动速度
    targetX += (mouseX * parallaxStrength - targetX) * 0.03;
    targetY += (mouseY * parallaxStrength - targetY) * 0.03;
    
    // 清除画布
    ctx.clearRect(0, 0, width, height);
    
    // 绘制背景
    if (backgroundImage.complete) {
      const scale = Math.max(width / backgroundImage.width, height / backgroundImage.height) * 1.2; // 增加缩放比例，确保背景充满
      const scaledWidth = backgroundImage.width * scale;
      const scaledHeight = backgroundImage.height * scale;
      
      ctx.drawImage(
        backgroundImage,
        -targetX - (scaledWidth - width) / 2,
        -targetY - (scaledHeight - height) / 2,
        scaledWidth,
        scaledHeight
      );
    }
    
    requestAnimationFrame(animate);
  }
  
  // 开始动画
  animate();
  
  // 监听窗口大小变化
  const handleResize = () => {
    width = window.innerWidth;
    height = window.innerHeight;
    canvas.width = width;
    canvas.height = height;
  };
  
  window.addEventListener('resize', handleResize);
  
  // 组件卸载时清理事件监听
  onBeforeUnmount(() => {
    window.removeEventListener('mousemove', handleMouseMove);
    window.removeEventListener('resize', handleResize);
  });
});
</script>
<style scoped>
.main-context {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
}

#bg-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}

.box-card {
  width: 400px;
  background-color: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.button {
  color: #409EFF;
}

/* 添加一些动画效果 */
.box-card {
  animation: fadeIn 0.5s ease-out;
  background: rgba(255, 255, 255, 0.7)
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 输入框悬停效果 */
:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409EFF;
}

/* 按钮悬停效果 */
:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}
</style>
